import {post, fetch} from '../../../utils/axios'

const state = {
  name: '新增发布',
  host: {items: [{ text: '', value: '' }]},
  valid: null,
  fields: {},
  build: {},
  emenu: false,
  dmenu: false,
  rdate: '',
  rtime: '',
  noteError: false,
  submitLoad: false,
  noteMsg: [],
  buildRules: [
    (v) => !!v || '请选择构建包'
  ],
  hostRules: [
    (v) => !v.length < 1 || '请选择主机'
  ],
  runtimeRules: [
    (v) => !!v || '请选择发布时间'
  ],
  rundateRules: [
    (v) => !!v || '请选择发布日期'
  ],
  noteRules: [
    (v) => !!v || '请填写备注'
  ],
  msg: {
    build: '',
    host: '',
    runtime: ''
  }
}

const mutations = {
  closeNewPublish (state) {
    // console.log(this._vm.$data.$$state.listPublish)
    this._vm.$data.$$state.listPublish.newDialog = false
  },
  savePublish (state, payload) {
    if (payload.validate()) {
      state.submitLoad = true
      state.fields.planTime = state.rdate + 'T' + state.rtime
      post('/publisher/',
        state.fields
      ).then((response) => {
        state.submitLoad = false
        this._vm.$data.$$state.listPublish.newDialog = false
      }).catch((error) => {
        if (error.response.data) {
          state.submitLoad = false
          let datas = error.response.data
          for (var name in datas) {
            state.msg[name] = datas[name]
            console.log(state.msg)
          }
        }
      })
    }
  },
  loadPublishSelect (state, payload) {
    let now = new Date()
    state.rtime = now.getHours() + ':' + now.getMinutes()
    state.rdate = now.getFullYear() + '-' + (parseInt(now.getMonth()) + 1) + '-' + now.getDate()
    state.fields.Project = payload
    fetch('/publisher/get_build/', {
      project: payload
    }).then((response) => {
      state.fields.build = []
      state.build = {items: [{ text: '', value: '' }]}
      let res = JSON.parse(response)
      state.build.items = res.data
    }).catch((error) => {
      state.etext = error.response
    })
    fetch('/publisher/get_host/', {
      project: payload
    }).then((response) => {
      state.fields.host = []
      state.host = {items: [{ text: '', value: '' }]}
      let res = JSON.parse(response)
      state.host.items = res.data
    }).catch((error) => {
      state.etext = error.response
    })
  }
}

const actions = {
  closeNewPublish ({commit}) {
    commit('closeNewPublish')
  },
  savePublish ({commit}, payload) {
    commit('savePublish', payload)
  },
  loadPublishSelect ({commit}, payload) {
    commit('loadPublishSelect', payload)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
